import re
import time

from django import forms
from django.core.validators import RegexValidator
from django.contrib.auth import login
from django.db.models import Q

from .models import MyUser
from boke import constants

# 创建手机号的正则校验器
mobile_validator = RegexValidator(r'^1[3-9]\d{9}$', '手机号码格式不正确')
# 创建邮箱正则校验器
email_validator=RegexValidator(r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?",message='邮箱格式不正确')
class CheckForm(forms.Form):
    email=forms.CharField(min_length=6,
                          validators=[email_validator,],
                           error_messages={
                               'max_length':'邮箱长度有误',
                               'min_length':'邮箱长度有误',
                               'required':'邮箱不能为空'
                           },)
    username = forms.CharField(label='用户名', max_length=20, min_length=5,
                               error_messages={
                                   'max_length': '用户名长度要小于20',
                                   'min_length': '用户名长度要大于4',
                                   'required': '用户名不能为空'
                               })
    password = forms.CharField(label='密码', max_length=20, min_length=6,
                               error_messages={
                                   'max_length': '密码长度要小于20',
                                   'min_length': '密码长度要大于5',
                                   'required': '用户名不能为空'
                               })
    password_repeat = forms.CharField(label='确认密码', max_length=20, min_length=6,
                                      error_messages={
                                          'max_length': '密码长度要小于20',
                                          'min_length': '密码长度要大于5',
                                          'required': '用户名不能为空'
                                      })


    def clean(self):

        #获取邮箱
        email=self.data.get('email')
        # 校验邮箱
        if MyUser.objects.filter(email=email).exists():
            raise forms.ValidationError('邮箱已注册')
        return email
    def clean_username(self):
        """
        校验用户名
        :return:
        """

        username = self.data.get('username')
        if MyUser.objects.filter(name=username).exists():
            return forms.ValidationError('用户名已存在！')
        return username

    def clean_password(self):
        """
        校验，密码
        :return:
        """
        # 校验密码是否一致
        password = self.data.get('password')
        password_repeat = self.data.get('password_repeat')
        if password != password_repeat:
            raise forms.ValidationError('两次密码不一致！')
        return password


class LoginForm(forms.Form):
    username = forms.CharField(error_messages={'required': '账户不能为空'})
    password = forms.CharField(max_length=20, min_length=6,
                               error_messages={
                                   'max_length': '密码长度要小于20',
                                   'min_length': '密码长度要大于6',
                                   'require': '密码不能为空'
                               })
    remember = forms.BooleanField(required=False)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)
    def clean_account(self):
        """
        校验用户账户
        :return:
        """
        username=self.cleaned_data.get('username')
        if not re.match(r'^\w{5,20}$', username) and (len(username) < 5 or len(username) > 20):
            raise forms.ValidationError('用户名格式不正确,请重新输入')
        return username

    def clean(self):
        """
        校验用户名密码，并实现登录逻辑
        :return:
        """
        cleaned_data = super().clean()
        username=cleaned_data.get('username')
        password=cleaned_data.get('password')
        remember=cleaned_data.get('remember')
        # 登录逻辑
        user_queryset = MyUser.objects.filter(Q(email=username) | Q(username=username))
        if user_queryset:
            user = user_queryset.first()
            if user.check_password(password):
                if remember:
                    #设置session过期时间
                    self.request.session.set_expiry(constants.USER_SESSION_EXPIRY)
                else:
                    self.request.session.set_expiry(0)
                login(self.request, user)
                self.request.session['username']=username
                # 将登陆时间保存到session中
                self.request.session["time"] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            else:
                self.request.session['username'] = '未登录'
                raise forms.ValidationError('用户名密码错误!')
        else:
            raise forms.ValidationError('用户账号不存在，请重新输入!')
